package com.situ.Servlet.Test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContext2 extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");//post乱码问题
		resp.setContentType("text/html;charset=utf-8");//服务器响应浏览器乱码问题
		ServletContext servletContext = getServletContext(); //创建servlet对象
		Integer count = (Integer) servletContext.getAttribute("count"); //get到count
//		if (count == null) {   //第一次访问，赋值为1，否则就+1；
//			count = 1;
//		}else {
//			count+=1;
//		}
		/**
		 * initServlet初始化后count=0
		 */
		count++;
		servletContext.setAttribute("count", count); //if完，set进去
		String name = (String) servletContext.getAttribute("name");//取出text1放进去的名字
//		System.out.println(name);
		System.out.println(count); //打印出来
		PrintWriter writer = resp.getWriter();//不经过jsp，直接浏览器打印
		writer.println("访问ServletContext的访客： " + count + "  " + name);
		writer.close();
	}
}
